<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('account.idNumber')"
    custom-class="dialog-min-width"
    :width="500"
    :destroy-on-close="true"
  >
    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formEdit"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('account.idNumber')">
            <el-input v-model="formEdit.idNumber" maxlength="18" clearable>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import utils from "../../utils/utils";
//   import apiAccount from "../api/account";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
import apiUser from "./api/user";

const formRef = ref();
const loading = ref(false);

const emit = defineEmits<{
  (event: "on-submit-success", idNumber: string, idNumberMask: string): void;
}>();

const state = reactive({
  dialogFormVisible: false,
});

const formEditOriginal = () => {
  return {
    idNumber: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  idNumber: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "change",
    },
  ],
});

const handleSubmit = () => {
  // 处理业务逻辑，触发关闭事件
  loading.value = true;

  apiUser
    .changeIdNumber(formEdit.idNumber)
    .then((response: any) => {
      loading.value = false;
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit.idNumber, response.data.data);
      }
    })
    .catch((err: any) => {
      loading.value = false;
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (row: any) => {
  // console.log("show", row);
  Object.assign(formEdit, formEditOriginal());
  if (row != undefined) {
    Object.assign(formEdit, row);
  }
  loading.value = false;
  state.dialogFormVisible = true;
};

defineExpose({
  show,
});
</script>
